<template>
  <div class="got">
    <div class="head"><strong>首页</strong> > 商品管理 > 分类参数</div>
    <el-card>
      <el-alert
        show-icon
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
      >
      </el-alert>
      <!-- 选择商品分类区 -->
      <el-row class="rows">
        <el-col>
          <span>选择商品分类:</span>
          <!-- 选择商品分类的基联选择框 -->
          <el-cascader
            v-model="gosy"
            :options="catelist"
            :props="sol"
            @change="handleChange"
            style="width: 30%"
            clearable
            class="cass"
          ></el-cascader>
        </el-col>
      </el-row>
      <el-tabs v-model="activeName" @tab-click="handtabClick">
        <el-tab-pane label="动态参数" name="many" :disabled="isbod">
          <el-button type="primary" :disabled="isbod" @click="godd"
            >添加参数</el-button
          >
          <el-table :data="manydata" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环生成的el-tag -->
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleClose(i, scope.row)"
                  class="tagg"
                  >{{ item }}</el-tag 
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="log(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  @click="remove(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only" :disabled="isbod">
          <el-button type="primary" :disabled="isbod" @click="godd"
            >添加属性</el-button
          >
          <el-table :data="onlydata" border stripe>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column
              label="商品名称"
              prop="attr_vals"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="log(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  @click="remove(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <el-dialog
      :title="'添加' + isname"
      :visible.sync="dialogVisible"
      width="30%"
      @close="closeclear"
    >
      <el-form
        :model="addForm"
        :rules="addform"
        ref="addFromRef"
        label-width="90px"
      >
        <el-form-item :label="isname" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="foy">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      :title="'修改' + isname"
      :visible.sync="dialog"
      width="30%"
      @close="closeclear"
    >
      <el-form
        :model="addForm"
        :rules="addform"
        ref="addFromRef"
        label-width="90px"
      >
        <el-form-item :label="isname" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialog = false">取 消</el-button>
        <el-button type="primary" @click="dia">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created() {
    this.getcatelist()
  },
  data() {
    return {
      dialog: false,
      addform: {
        attr_name: [
          {
            required: true,
            messgae: '请输入分类名称',
            trigger: 'blur',
          },
        ],
      },
      addForm: {
        attr_name: '',
        attr_id: '',
      },
      dialogVisible: false,
      onlydata: [],
      manydata: [],
      activeName: 'many',
      gosy: [],
      catelist: [],
      sol: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
      },
    }
  },
  methods: {
    async getcatelist() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      console.log(res);
      this.catelist = res.data
    },
    async handleChange() {
      if (this.gosy.length === 0) {
        return (this.manydata = []), (this.onlydata = [])
      }
      const { data: res } = await this.$http.get(
        `categories/${this.isid}/attributes`,
        { params: { sel: this.activeName } }
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      console.log(res.data)
      this.manydata = res.data
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : [] //返回一个数组
        this.$set(item, 'inputVisible', false)
        this.$set(item, 'inputValue', '')
      })
      console.log(res.data)
    },
    async handtabClick() {
      const { data: res } = await this.$http.get(
        `categories/${this.isid}/attributes`,
        { params: { sel: this.activeName } }
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      console.log(res.data)
      if (this.activeName === 'many') {
        this.manydata = res.data
        res.data.forEach((item) => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : [] //返回一个数组
          this.$set(item, 'inputVisible', false)
          this.$set(item, 'inputValue', '')
        })
      } else {
        this.onlydata = res.data
      }
    },
    godd() {
      this.dialogVisible = true
    },
    closeclear() {
      this.$refs.addFromRef.resetFields()
    },
    foy() {
      this.$refs.addFromRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          `categories/${this.gosy[2]}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName,
          }
        )
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.handtabClick()
        this.dialogVisible = false
      })
    },
    log(sf) {
      ;(this.addForm.attr_name = sf.attr_name),
        (this.addForm.attr_id = sf.attr_id)
      this.dialog = true
    },
    async dia() {
      this.$refs.addFromRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          `categories/${this.gosy[2]}/attributes/${this.addForm.attr_id}`,
          {
            attr_sel: this.activeName,
            attr_name: this.addForm.attr_name,
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.handtabClick()
        this.dialog = false
      })
    },
    async remove(id) {
      //console.log(id);
      const bug = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      //console.log(bug)
      //成功时是confirm
      //取消是cancel
      if (bug !== 'confirm') {
        this.$message.info('已取消删除')
      } else {
        const { data: res } = await this.$http.delete(
          `categories/${this.gosy[2]}/attributes/${id}`
        )
        if (res.meta.status !== 200) {
          return this.$message.error('删除用户失败')
        }
        this.$message.success('删除成功')
        this.handtabClick()
      }
    },
    showInput(ms) {
      ms.inputVisible = true
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleInputConfirm(row){
        console.log(row);
  //当用户在文本框中按下enter键或者焦点离开时都会触发执行
  //判断用户在文本框中输入的内容是否合法
  if(row.inputValue.trim().length===0){
    row.inputValue = ''
    row.inputVisible = false
    return
  }

  // row.inputVisible = false
  //如果用户输入了真实合法的数据，需要保存起来
  row.attr_vals.push(row.inputValue.trim())
  console.log(row);
  row.inputValue = ''
  row.inputVisible = false

  this.saveAttrVals(row)
},
    handleClose(index, row) {
      //删除对应索引的参数可选项
      row.attr_vals.splice(index, 1)
      //调用函数，完成保存可选项的操作
      this.saveAttrVals(row)
    },
   async saveAttrVals(row){
       const {data:res} = await this.$http.put(`categories/${this.gosy[2]}/attributes/${row.attr_id}`,
  {attr_name:row.attr_name,attr_sel:row.attr_sel,attr_vals:row.attr_vals.join(' ')})

  if (res.meta.status !== 200) {
    return this.$message.error('修改参数项失败')
  }

  this.$message.success('修改参数项成功')

   }
  },
  computed: {
    isbod() {
      if (this.gosy.length !== 3) {
        return true
      } else {
        return false
      }
    },
    isid() {
      if (this.gosy.length === 3) {
        return this.gosy[2]
      } else {
        return null
      }
    },

    isname() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    },
  },
}
</script>

<style lang='less' scoped>
.head {
  margin-left: 20px;
  margin-top: 25px;
  font-size: 14px;
  margin-bottom: 20px;
}
.rows {
  margin: 10px;
}
.tagg {
  margin: 10px;
}
.input-new-tag {
  width: 100px;
}
.cass{
    margin-left: 20px;
}
</style>